﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Copad.BusinessCard.BLL;
using Copad.BusinessCard.Model;
using Newtonsoft.Json;

public partial class Remark : BusinessCardPageBase
{
    CardRemarkBLL remarkBLL = new CardRemarkBLL();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string cardid = Request["cardid"];
        if (string.IsNullOrEmpty(cardid))
        {
            return;
        }

        if (!this.FileUpload1.HasFile)
        {
            return;
        }
        string extName = Manager.GetFileExtName(this.FileUpload1.FileName);
        if (string.IsNullOrEmpty(extName))
        {
            extName = "";
        }
        string filename = Guid.NewGuid().ToString() + extName;
        try
        {
            this.FileUpload1.SaveAs(Manager.RemarkImageRootPath + filename);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(this.btnAdd, typeof(string), "", "result=" + JsonConvert.SerializeObject(new { Result = false, Message = "保存图片出错，请重试或联系管理员！" }), true);
            return;
        }

        RemarkTypeEnum type;
        if (this.FileUpload1.PostedFile.ContentType.ToLower().StartsWith("image"))
        {
            type = RemarkTypeEnum.ImageFileName;
        }
        else
        {
            type = RemarkTypeEnum.FileName;
        }
        CardRemark remark = new CardRemark { CardID = cardid, Remark = filename, Type = type, UserID = Manager.CurrentUser.User.ID, Username = Manager.CurrentUser.User.Username, RemarkDate = DateTime.Now };

        var result = remarkBLL.Validate(remark);
        if (!result.Successful)
        {
            ScriptManager.RegisterClientScriptBlock(this.btnAdd, typeof(string), "", "result=" + JsonConvert.SerializeObject(new { Result = false, Message = "数据不合法：<br/>" + result.Message }), true);
            return;
        }

        try
        {
            remarkBLL.Insert(remark);
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterClientScriptBlock(this.btnAdd, typeof(string), "", "result=" + Manager.DatabaseFailureJsonText, true);
        }
    }
}